package com.ccz.demo.bookdemo.javayibubianchengshizhan.c2.chapter3;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;

public class Demo3_3_4 {
    // 1.异步任务，返回future
    public static CompletableFuture<String> doSomethingOne(String encodedCompanyId) {
        // 1.1创建异步任务
        return CompletableFuture.supplyAsync(new Supplier<String>() {
            @Override
            public String get() {
                // 1.1.1休眠1s，模拟任务计算
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 1.1.2 解密，并返回结果
                String id = encodedCompanyId;
                return id;
            }
        });
    }

    // 2.开启异步任务，返回future
    public static CompletableFuture<String> doSomethingTwo(String companyId) {
        return CompletableFuture.supplyAsync(new Supplier<String>() {
            @Override
            public String get() {
                // 2.1 休眠3s，模拟计算
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
                }
               // 2.2 查询公司信息，转换为str，并返回
                String str = companyId + ":alibaba";
                return str;
            }
        });
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // I，等doSomethingOne执行完毕后，接着执行doSomethingTwo
        long start = System.currentTimeMillis();
//        CompletableFuture<String> result = doSomethingOne("123").thenCompose(id -> doSomethingTwo(id));
//        System.out.println(result.get());

        // 多个请求合并为一个
        List<CompletableFuture<String>> futureList = new ArrayList<>();
        futureList.add(doSomethingOne("1"));
        futureList.add(doSomethingOne("2"));
        futureList.add(doSomethingOne("3"));
        futureList.add(doSomethingOne("4"));
        // allOf等待全部完成返回， anyOf有一个返回就行
        CompletableFuture<Void> result = CompletableFuture.allOf(futureList.toArray(new CompletableFuture[futureList.size()]));
        System.out.println(result.get());
        System.out.println(System.currentTimeMillis() - start);
    }


}
